package com.xl.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xl.yygh.hosp.repository.DepartmentRepository;
import com.xl.yygh.hosp.service.DepartmentService;
import com.xl.yygh.model.model.hosp.Department;
import com.xl.yygh.model.vo.hosp.DepartmentQueryVo;
import com.xl.yygh.model.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author XiangLiang
 * @date 2023/10/24 16:44
 * @description
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Resource
    private DepartmentRepository departmentRepository;

    /**
     * 保存科室信息
     * @param map 科室信息
     */
    @Override
    public void saveDepartment(Map<String, Object> map) {
        Department department = JSONObject.parseObject(JSONObject.toJSONString(map), Department.class);

        // 根据医院编号和科室编号获取Department实体
        Department targetDepartment = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        // targetDepartment不为空，修改
        if (targetDepartment != null) {
            targetDepartment.setUpdateTime(new Date());
            targetDepartment.setIsDeleted(0);
            departmentRepository.save(targetDepartment);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    /**
     * 科室分页查询
     * @param page 当前页
     * @param limit 每页记录数
     * @param departmentQueryVo 查询VO
     * @return 科室分页结果
     */
    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        // 设置分页条件(0为第一页)
        Pageable pageable = PageRequest.of(page - 1, limit);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        // 创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching()  // 构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)  // 改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);  // 改变默认大小写忽略方式：忽略大小写
        // 创建Example实例
        Example<Department> example = Example.of(department, matcher);

        Page<Department> pageList = departmentRepository.findAll(example, pageable);
        return pageList;
    }

    /**
     * 删除科室信息
     * @param hoscode 医院编号
     * @param depcode 科室编号
     */
    @Override
    public void removeDepartment(String hoscode, String depcode) {
        // 根据医院编号和科室编号获取Department实体
        Department department = departmentRepository
                .getDepartmentByHoscodeAndDepcode(hoscode, depcode);

        // 根据ID删除科室信息
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }

    /**
     * 根据医院编号，查询医院所有科室列表
     * @param hoscode 医院编号
     * @return 医院所有科室列表
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        // 创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        // 根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);
        // 所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        // 根据大科室编号  bigCode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> departmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        // 遍历map集合 departmentMap
        for(Map.Entry<String,List<Department>> entry : departmentMap.entrySet()) {
            // 大科室编号
            String bigcode = entry.getKey();
            // 大科室编号对应的全局数据
            List<Department> deparment1List = entry.getValue();
            // 封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(deparment1List.get(0).getBigname());

            // 封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for(Department department: deparment1List) {
                DepartmentVo departmentVo2 =  new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                // 封装到list集合
                children.add(departmentVo2);
            }
            // 把小科室list集合放到大科室children里面
            departmentVo1.setChildren(children);
            // 放到最终result里面
            result.add(departmentVo1);
        }
        // 返回
        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department != null) {
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }
}
